package cn.tedu.csmall.cart.webapi.controller;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.pojo.cart.dto.CartAddDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("/base/cart")
@Api(tags = "购物车管理")
public class CartController {

    @Autowired
    private ICartService cartService;

    @PostMapping("/add")
    @ApiOperation("新增购物车商品")
    public JsonResult cartAdd(CartAddDTO cartAddDTO){
        cartService.cartAdd(cartAddDTO);
        return JsonResult.ok("新增购物车商品完成!");
    }

    // 执行RestTemplate调用对象的装配
    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/delete")
    @ApiOperation("删除购物车中商品")
    @ApiImplicitParams({
        @ApiImplicitParam(value = "用户ID",name="userId",example = "UU100",required = true),
        @ApiImplicitParam(value = "商品编号",name="commodityCode",
                                                        example = "PC100",required = true)
    })
    public JsonResult deleteUserCart(String userId,String commodityCode){
        // 准备发送RestTemplate请求,实现库存的减少
        // 通用的操作是先确定要调用的方法的url
        //     url="http://nacos-stock/base/stock/reduce/...."
        String url="http://localhost:20003/base/stock/reduce/count" +
                "?commodityCode={1}&reduceCount={2}";
        // 发起调用,
        // getForObject方法参数:第一个参数是url路径,第二个参数是返回值类型的反射
        // 从第三个开始,是url中使用{1}标记的占位符,第四个参数就是对应{2}的占位符,以此类推
        JsonResult jsonResult=restTemplate.getForObject(url,JsonResult.class,
                            commodityCode,5);
        System.out.println("rest调用完毕,返回值:"+jsonResult);
        // 原有的删除购物车的方法
        cartService.deleteUserCart(userId,commodityCode);
        return JsonResult.ok("删除购物车商品完成!");
    }




}
